package cn.alm.spring03tx.dao;

import cn.alm.spring03tx.entity.Book;
import jakarta.annotation.Resource;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.Map;

@Component
public class BookDao {

    @Resource
    JdbcTemplate jdbcTemplate;

    public Book getBookById(Integer id) {
        // 1、查询图书SQL
        String url = "select * from tb_book where id = ?";

        // 2、执行查询
        Book book = jdbcTemplate.queryForObject(url, new BeanPropertyRowMapper<>(Book.class), id);
        return book;
    }

    public void addBook(Book book) {
        // 1、添加图书SQL
        String url = "insert into tb_book values (null, ?, ?, ?)";
        int update = jdbcTemplate.update(url, book.getName(), book.getPrice(), book.getStock());
        if (update == 0) {
            System.out.println("添加失败");
        } else {
            System.out.println("添加成功");
        }
    }

    public void updateBookStockById(Integer id, Integer num) {
        // 首先检查库存是否充足
        Book bookById = getBookById(id);
        Integer stock = bookById.getStock();
        if (stock < num) {
//            System.out.println("库存不足");
            throw new RuntimeException("库存不足");
        }
        // 2、更新库存SQL
        stock -= num;
        String url = "update tb_book set stock = ? where id = ?";
        int update = jdbcTemplate.update(url, stock, id);
        if (update == 0) {
            System.out.println("更新失败");
        } else {
            System.out.println("更新成功");
        }
    }

    public void sellBook(Integer id) {
        // 先查询出此图书的库存
        Book bookById = getBookById(id);
        Integer stock = bookById.getStock();
        if (stock > 0) {
            // 2、更新库存SQL
            stock--;
            String url = "update tb_book set stock = ? where id = ?";
            int update = jdbcTemplate.update(url, stock, id);
            if (update == 0) {
                System.out.println("更新失败");
            } else {
                System.out.println("更新成功");
            }
        } else {
//            System.out.println("库存不足");
            throw new RuntimeException("库存不足");
        }
    }

}
